package com.umbacos.udm.client.model;

import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.umbacos.udm.client.arch.MinMax;
import com.umbacos.udm.client.arch.ResizePanel;
import com.umbacos.udm.client.arch.ResizePanel.PanelResizeListener;

public class View extends ResizePanel implements PanelResizeListener {

	private final ScrollPanel spContent = new ScrollPanel();
	private final DecoratorPanel dpContent = new DecoratorPanel();
	private final VerticalPanel vpContent = new VerticalPanel();
	private final Grid grHeader = new Grid();
	private final MinMax mm;

	public View(){

		RootLayoutPanel rlp=RootLayoutPanel.get();
		addPanelResizedListener(this);
		add(dpContent);
		dpContent.add(vpContent);
		vpContent.add(grHeader);
		vpContent.add(spContent);

		spContent.setSize(rlp.getOffsetWidth() - 200 + "px", "150px");

		mm=new MinMax(this);
		
		grHeader.setWidth(rlp.getOffsetWidth()-200 + "px");
		grHeader.resize(1, 2);
		grHeader.setCellSpacing(0);
		grHeader.setCellPadding(0);
		grHeader.getColumnFormatter().setWidth(0, rlp.getOffsetWidth() - 250 + "px");
		grHeader.getColumnFormatter().setWidth(1, "50px");
		grHeader.getCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT,HasVerticalAlignment.ALIGN_MIDDLE);
		grHeader.getCellFormatter().setAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT,HasVerticalAlignment.ALIGN_MIDDLE);
		grHeader.getRowFormatter().setStyleName(0, "header");
		grHeader.setWidget(0, 1, mm);
	}

	public void setTitle(Widget w) {
		insert(w, 0);
	}

	public void setContent(Widget w) {
		spContent.setWidget(w);
	}

	public Widget getContent() {
		return spContent.getWidget();
	}

	public void setHeader(Widget w) {
		grHeader.setWidget(0, 0, w);
	}

	public Grid getHeader() {
		return (Grid)grHeader.getWidget(0, 0);
	}

	public int getIndex() {
		return ((VerticalPanel) getParent()).getWidgetIndex(this);
	}

	public void moveDown() {
		if (getIndex() == ((VerticalPanel) getParent()).getWidgetCount() - 1)
			return;
		((View) ((VerticalPanel) getParent()).getWidget(getIndex() + 1)).moveUp();
	}

	public void moveUp() {
		if (getIndex() > 0)
			((VerticalPanel) getParent()).insert(this, getIndex() - 1);
	}

	@Override
	public void onResized(Integer width, Integer height) {
		if (height > 64)
			spContent.setHeight(height - grHeader.getOffsetHeight() - 64 + "px");
	}

	public void resize(int width, int height) {
		spContent.setHeight(height + "px");
		setHeight(height + grHeader.getOffsetHeight() + "px");
	}
	
}
